package com.example.elasticsearch;

import com.example.elasticsearch.entity.Goods;
import com.example.elasticsearch.mapper.GoodsMapper;
import com.example.elasticsearch.mapper.GoodsRepository;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.FetchSourceFilterBuilder;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SourceFilter;
import org.springframework.test.context.junit4.SpringRunner;

/**
 * 必须添加类描述
 *
 * @author HTJT
 * @date 2023/3/7 15:11
 * @version 1.0
 */
@SpringBootTest
@RunWith(SpringRunner.class)
public class resultFiler {

    @Autowired
    private GoodsMapper goodsMapper;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 过滤source获取部分字段内容
     */
    @Test
    public void sourceFilter() {
        //查询条件(词条查询：对应ES query里的match)
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery()
                .must(QueryBuilders.matchQuery("title", "金立"))
                .must(QueryBuilders.matchQuery("categoryName", "手机"))
                .filter(QueryBuilders.rangeQuery("price").gt(1000).lt(2000));

        // 不需要获取source结果集
        SourceFilter sourceFilter = new FetchSourceFilterBuilder().withIncludes("title", "categoryName").build();

        //创建查询条件构建器SearchSourceBuilder(对应ES外面的大括号)
        NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder()
                .withQuery(boolQueryBuilder)
                .withSourceFilter(sourceFilter)
                .build();
        //查询,获取查询结果
        SearchHits<Goods> search = elasticsearchRestTemplate.search(nativeSearchQuery, Goods.class);

        //获取总记录数
        System.out.println("totalHits = " + search.getTotalHits());
        //获取值返回
        search.getSearchHits().stream().map(SearchHit::getContent).forEach(System.out::println);
    }

}
